package model;

import java.util.Iterator;
import java.util.Vector;

import listener.ParticipantChangeEvent;
import listener.ParticipantChangeListener;
import view.Launch;
import clock.Clock;
import clock.Minute;
import clock.Second;

public class CurrentParticipant implements Runnable {
	private final static int ME_WAIT_LONG_TIME = 100;
	
	private Thread thread;
	private Participant p;
	private Participant prev;
	private Vector<ParticipantChangeListener> listeners;
	
	public CurrentParticipant() {
		this.p = null;
		this.prev = null;
		listeners = new Vector<ParticipantChangeListener>();
		
		thread = new Thread(this);
		thread.start();
	}
	
	public CurrentParticipant(Participant p) {
		this.p = p;
		this.prev = p;
		listeners = new Vector<ParticipantChangeListener>();
		
		thread = new Thread(this);
		thread.start();
	}
	
	public Participant getParticipant() {
		return p;
	}
	
	public void setParticipant(Participant p) {
		this.p = p;
	}
	
	public Clock getClock() {
		return p.getClock();
	}
	
	public Minute getMinute() {
		return getClock().getMinute();
	}
	
	public Second getSecond() {
		return getClock().getSecond();
	}
	
	public void addParticipantChangeListener(ParticipantChangeListener e) {
		if (listeners.contains(e))
			return;
		listeners.add(e);
	}
	
	public void removeParticipantChangeListener(ParticipantChangeListener e) {
		if (!listeners.contains(e))
			return;
		listeners.remove(e);
	}
	
	public void removeParticipantChangeListeners() {
		listeners.clear();
	}

	private void createEvent() {
		ParticipantChangeEvent e = new ParticipantChangeEvent(p);
		Iterator<ParticipantChangeListener> i = listeners.iterator();
		while (i.hasNext())
			i.next().participantChange(e);
	}
	
	public void run() {
		while (true) {
			if (prev != p) {
				prev = p;
				createEvent();
			} try {
				Thread.sleep(ME_WAIT_LONG_TIME);
			} catch (InterruptedException e) {
				if (Launch.DEBUG) System.err.println(e);
			}
		}
	}
}
